-- NewTeamSettingPanel

local IMVoiceRender = app:getClass("IMVoiceRender")
local IMVoiceBtn = app:getClass("IMVoiceBtn")

local MAX_LEVEL = tonumber(GD:getSystemPar("maxlvforpro",60))
local MAX_WORD_LEN = 60

local ClassRef = app.mvc.createPanelClass(...)

local dutyName = {
	[1] = L("dutyClass1"),
	[2] = L("dutyClass2"),
	[3] = L("dutyClass3")
}
local dutyIndexOfData = {
	[1] = "needTank",
	[2] = "needDPS",
	[3] = "needHeal"
}

function ClassRef.create(node)
	local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.NewTeamSettingInfoNode))
	if node == nil then
		ccui.Helper:doLayout(sprite)
	end
	sprite:init()
	return sprite
end

function ClassRef:init(data)
	self.super.init(self, data)

	self._data_temp = nil -- 拷贝的self._data用来进行操作。避免直接操作self._data污染NewteamVo中的数据
	self._isMyTeamLeader = false -- 是否我队长？

	-- 以下：职责设置相关操作
	self._dutyPanelList = {}
	local dutyChildrenList = self._ui["Panel/Panel_1/Panel_duty"]:getChildren()
	local dutyChildrenCount = self._ui["Panel/Panel_1/Panel_duty"]:getChildrenCount()
	for i = 1, dutyChildrenCount do
		local dutyTemp = dutyChildrenList[i]
		dutyTemp:getChildByName("Panel"):addTouchEventListener(function(sender, eventType)
			if eventType == ccui.TouchEventType.ended then
				if not self._isMyTeamLeader then -- 我不是队长？
					display.pushToast( L("lua_code_text_498") )
					return
				end

				local statusAfterChanged = not self._data_temp[ dutyIndexOfData[ i ] ] -- 改变之后的职责需求状态

				if not statusAfterChanged then -- 改变之后为false、需要提示
					-- 你确定要拒绝 %s 型玩家的入队申请吗？
					local creataeTeamDialog = display.newConfirmDialog( string.format( L("lua_code_text_217"), dutyName[i] ),
						function() -- 确定
							self:setDutySelected( i, statusAfterChanged )
						end)
					UIHandler:addPopDialog( creataeTeamDialog )
				else
					self:setDutySelected( i, statusAfterChanged )
				end
			end
		end)
		dutyTemp:getChildByName("Panel"):getChildByName("name"):setString( dutyName[i] )

		dutyTemp:getChildByName("Panel"):getChildByName("icon_tk"):setVisible( 1 == i )
		dutyTemp:getChildByName("Panel"):getChildByName("icon_dps"):setVisible( 2 == i )
		dutyTemp:getChildByName("Panel"):getChildByName("icon_zl"):setVisible( 3 == i )

		display.setCascadeOpacityEnabled(dutyTemp, true)
		self._dutyPanelList[i] = dutyTemp
	end

	-- 自动同意按钮
	self._ui["Panel/Panel_1/Panel_bom/selected_btn"]:addClickEventListener(function()
			if not self._isMyTeamLeader then -- 我不是队长？
				display.pushToast( L("lua_code_text_498") )
				return
			end

			if self._data:isInCrossMatch() then
				display.pushToast(L("CrossServerTips16"))
				return
			end

			local autoApproveAfterChanged = not self._data_temp.autoApprove -- 改变之后的"自动同意"状态
			self:setAutoAgreeSelected( autoApproveAfterChanged )
		end)

	-- minLv maxLv
	self:_initPickerView()

	-- edit
	local function onEditCallback(strEventName,sender)
		local edit = sender
		if strEventName == "changed" then
			local text = edit:getText()
			local ulen = string.ulen(text)
			if ulen > MAX_WORD_LEN then
				local newStr = string.usubstr(text,MAX_WORD_LEN)
				if text~=newStr then
					edit:setText(newStr)
					text = newStr
					display.pushToast(string.format(L("max_input_char"), MAX_WORD_LEN))
				end
			end
		elseif strEventName == "ended" then
			local text = edit:getText()
			self:setRecruitMessage(text)
		end
	end
	local textField = self._ui["Panel/Panel_2/TextField"]
	self._editText = display.replaceTextFieldWithEditBox(textField, cc.EDITBOX_INPUT_MODE_ANY)
	self._editText:setPlaceholderFontColor(cc.c3b(255, 225, 132))
	self._editText:registerScriptEditBoxHandler(onEditCallback)

	-- 录音
	self._recordPanel = self._ui["Panel/Panel_2/Panel_record"]
	self._voiceRender = IMVoiceRender.create( self._ui["Panel/Panel_2/Panel_record/Button_close"], nil)
	self._voiceRender:onRecordEnd(function(fileId, filePath, duration)
		if not self._isMyTeamLeader then -- 我不是队长？
			display.pushToast( L("lua_code_text_498") )
			return
		end

		print("_voiceRender", fileId, filePath, duration)

		if fileId then
			self._data_temp.memoAudio = fileId
			self._data_temp.audioPath = filePath
			self._data_temp.audioDuration = duration

			self._recordPanel:setVisible(false)
			self._playPanel:setVisible(true)
			self._voiceBtn:setData(self._data_temp)
		end
	end)

	-- 删除录音
	self._playPanel = self._ui["Panel/Panel_2/Panel_play"]
	self._delBtn = self._playPanel:getChildByName("Button_close")
	self._delBtn:addClickEventListener(function()
		if not self._isMyTeamLeader then -- 我不是队长？
			display.pushToast( L("lua_code_text_498") )
			return
		end

		self._recordPanel:setVisible(true)
		self._playPanel:setVisible(false)

		if self._voiceBtn:isInPlay() then
			executeFunc(self._onPanelHandler, "TeamSetting_stopPlay")
		end
		self._data_temp.memoAudio = ""
		self._data_temp.audioPath = ""
		self._data_temp.audioDuration = 0
	end)

	-- 播放录音
	local playNode = self._playPanel:getChildByName("ProjectNode_1")
	self._voiceBtn = IMVoiceBtn.create(playNode)
	self._voiceBtn:stopPlay()
	self._voiceBtn:onBtnClick(function()
		if self._data_temp:hasAudioFile() then
			if self._voiceBtn:isInPlay() then
				executeFunc(self._onPanelHandler, "TeamSetting_stopPlay")
			else
				executeFunc(self._onPanelHandler, "TeamSetting_playAudio", self._voiceBtn)
			end
		else
			-- 语音文件需要下载之后才能播放
			self._voiceBtn:setTouchEnabled(false)
			local fileId = self._data_temp.memoAudio
			executeFunc(self._onPanelHandler, "TeamSetting_loadAudio", fileId,
				function(fileId, filePath)
					if tolua.isnull(self) then return end
					print("_voiceBtn download", fileId, filePath)
					self._voiceBtn:setTouchEnabled(true)
					if fileId then
						-- 下载成功
						self._data_temp.audioPath = filePath
						executeFunc(self._onPanelHandler, "TeamSetting_playAudio", self._voiceBtn)
					else
						display.pushToast(L("lua_code_text_467"))
					end
				end)
		end
	end)
end

-- 旧代码，初始化：等级选择器
function ClassRef:_initPickerView()
	-- PickerView  初始化
	local numPanel = self._ui["Panel/Panel_1/Panel_lv"]
	local minPanel = numPanel:getChildByName("min")
	local maxPanel = numPanel:getChildByName("max")

	local minSize = minPanel:getContentSize()
	local minAnchor = minPanel:getAnchorPoint()
	local minPosition = cc.p(minPanel:getPosition())

	local maxAnchor = maxPanel:getAnchorPoint()
	local maxPosition = cc.p(maxPanel:getPosition())

	local minPickerViewName = "minPickerViewName"
	local maxPickerViewName = "maxPickerViewName"
	numPanel:removeChildByName(minPickerViewName)
	numPanel:removeChildByName(maxPickerViewName)

	local cellSize = cc.size(minSize.width,30)
	local count = MAX_LEVEL
	local function createCells() -- 关卡要求等级区间
		local cells = {}
		for i = 1, count do
			local content = "" .. i
			local text = ccui.Text:create(content, Res.font, 24)
			text:setColor( cc.c3b( 255, 225, 132 ) )

			local cell = ccui.Layout:create()
			table.insert(cells,cell)
			cell:addChild(text)
			cell:setContentSize(cellSize)
			text:setPosition(cc.p(cellSize.width * 0.5,cellSize.height * 0.5))
			cell:setBackGroundColor(cc.c3b(255 - i * 10,i * 10,i * 10))
			cell:setBackGroundColorType(ccui.LayoutBackGroundColorType.none)
			cell:setTouchEnabled(true)
		end
		return cells
	end

	-- minPickerView
	self._minPickerView = custom.PickerView:create()
	self._minPickerView:setDirection(ccui.ScrollViewDir.vertical)
	self._minPickerView:setContentSize(cc.size(cellSize.width, cellSize.height))
	self._minPickerView:setClippingEnabled(false)
	self._minPickerView:setBackGroundColorType(ccui.LayoutBackGroundColorType.none)
	self._minPickerView:setBackGroundColor(cc.c3b(0,255,0))
	self._minPickerView:setBackGroundImageOpacity(255)

	local cells = createCells()
	for i = 1, count do
		local cell = cells[i]
		self._minPickerView:pushBackCustomItem(cell)
	end

	self._minPickerView:addEventListener(function(sender,event,idx)
		local selMinLevel = idx + 1
		local max = self._maxPickerView:getPickedIndex() + 1
		if selMinLevel >= max then -- 上界、手动设置的
			selMinLevel = max
		end
		-- if selMinLevel <= self._minlv then -- 关卡要求的下界
		-- 	self._minPickerView:pickTo(self._minlv)
		-- end
		if selMinLevel ~= self._data_temp.minLevel then
			self._data_temp.minLevel = selMinLevel
		end
		self._minPickerView:pickTo( selMinLevel )
	end)
	self._minPickerView:setPosition(minPosition);
	self._minPickerView:setAnchorPoint(minAnchor)
	numPanel:addChild(self._minPickerView)
	self._minPickerView:setName(minPickerViewName)

	-- maxPickerView
	self._maxPickerView = custom.PickerView:create()
	self._maxPickerView:setDirection(ccui.ScrollViewDir.vertical)
	self._maxPickerView:setContentSize(cc.size(cellSize.width, cellSize.height))
	self._maxPickerView:setClippingEnabled(false)
	self._maxPickerView:setBackGroundColorType(ccui.LayoutBackGroundColorType.none)
	self._maxPickerView:setBackGroundColor(cc.c3b(0,255,0))
	self._maxPickerView:setBackGroundImageOpacity(0)
	cells = createCells()
	for i = 1, count do
		local cell = cells[i]
		self._maxPickerView:pushBackCustomItem(cell)
	end
	self._maxPickerView:addEventListener(function(sender,event,idx)
		local selMaxLevel = idx + 1
		local min = self._minPickerView:getPickedIndex() + 1
		if selMaxLevel <= min then -- 关卡要求的下界、手动设置的
			selMaxLevel = min
		end
		-- if selMaxLevel >= self._maxlv then -- 关卡要求的上界、配置表中配置的最大等级
		-- 	self._maxPickerView:pickTo(self._maxlv)
		-- end
		if selMaxLevel ~= self._data_temp.maxLevel then
			self._data_temp.maxLevel = selMaxLevel
		end
		self._maxPickerView:pickTo( selMaxLevel )
	end)
	self._maxPickerView:setPosition(maxPosition)
	self._maxPickerView:setAnchorPoint(maxAnchor)
	numPanel:addChild(self._maxPickerView)
	self._maxPickerView:setName(maxPickerViewName)
end

-- data = newTeamVo
function ClassRef:refresh()
	if self._data then
		self._data_temp = self._data.recruitInfo:cloneVo()
		self._minPickerView:pickTo( self._data_temp.minLevel )
		self._maxPickerView:pickTo( self._data_temp.maxLevel )

		for i = 1, 3 do
			self:setDutySelected( i, self._data_temp[ dutyIndexOfData[ i ] ] )
		end

		self:setAutoAgreeSelected( self._data_temp.autoApprove )
		self._editText:setText( self._data_temp.memoText )


		local hasAudio = self._data_temp:hasAudio()
		if hasAudio then
			self._voiceBtn:setData(self._data_temp)
		else
			self._voiceBtn:setData()
		end

		if self._data:isLeader( UD.player.uid ) then -- 队长？
			self._isMyTeamLeader = true

			self._recordPanel:setVisible(not hasAudio)
			self._playPanel:setVisible(hasAudio)
			self._delBtn:setVisible(true)

			self._minPickerView:setTouchEnabled( true )
			self._maxPickerView:setTouchEnabled( true )

			self._editText:setTouchEnabled( true )

			self._ui["Panel/Panel_1/Panel_bom/selected_btn"]:setTouchEnabled( true )
			self._ui["Panel/Panel_1/Panel_bom/selected_btn"]:setColor( display.COLOR_WHITE )
		else
			self._isMyTeamLeader = false

			self._recordPanel:setVisible(false)
			self._playPanel:setVisible(hasAudio)
			self._delBtn:setVisible(false)

			self._minPickerView:setTouchEnabled( false )
			self._maxPickerView:setTouchEnabled( false )

			self._editText:setTouchEnabled( false )
			self._editText:setPlaceHolder(L("lua_code_text_506"))

			self._ui["Panel/Panel_1/Panel_bom/selected_btn"]:setTouchEnabled( false )
			self._ui["Panel/Panel_1/Panel_bom/selected_btn"]:setColor( display.COLOR_GRAY )
		end
		-- 海外版没有语音功能
		if app:getPublisher() ~= Enums.Publisher.tencent then
			self._recordPanel:setVisible(false)
			self._playPanel:setVisible(false)
			self._ui["Panel/Panel_2/tlt04"]:setVisible(false)
			self._ui["Panel/Panel_bg/bg02/bg03"]:setVisible(false)
			self._ui["Panel/Panel_bg/bg02/bg06"]:setVisible(false)
			self._ui["Panel/Panel_bg/bg02/bg"]:setVisible(true)
		end
	end
end

-- 设置职责选中情况
function ClassRef:setDutySelected( dutyIdx, chosen )
	assert( dutyIdx <= 3, " ----------->>>>>>> 索引越界 " )

	self._data_temp[ dutyIndexOfData[ dutyIdx ] ] = chosen
	self._dutyPanelList[dutyIdx]:getChildByName("Panel"):getChildByName("choose"):setVisible( chosen )

	if chosen then
		self._dutyPanelList[dutyIdx]:setOpacity(255) -- 父子控件 color、opacity 关闭了默认向下传递
	else
		self._dutyPanelList[dutyIdx]:setOpacity(128)
	end
end

-- 设置自动申请选中情况
function ClassRef:setAutoAgreeSelected( selected )
	self._data_temp.autoApprove = selected
	self._ui["Panel/Panel_1/Panel_bom/selected_btn"]:setBright( not selected )
end

-- 设置标题显示方式
function ClassRef:setTitleShownWay( isMyTeam )
	self._ui["Panel/Panel_tlt_set"]:setVisible( isMyTeam )
	self._ui["Panel/Panel_tlt_data"]:setVisible( not isMyTeam )
end

-- 设置招募留言
function ClassRef:setRecruitMessage( str )
	if self._data_temp then
		local function checkCB( strTemp )
			if self and self._ui then
				self._editText:setText( strTemp )
				self._data_temp.memoText = str
			end
		end
		if app:isNeedCheckInput() then
			app:checkInput(str, function(response,errorMsg,code)
				if code == 200 then
					if response and response.result then
						str = response.result
						checkCB( str )
					end
				else
					display.pushToast(L("network_error"))
				end
			end, true)
		else
			checkCB( str )
		end
	end
end

function ClassRef:removeVoiceBtn()
	if self._voiceBtn:isInPlay() then
		executeFunc(self._onPanelHandler, "TeamSetting_stopPlay")
	end
end

-- 返回任何修改之后的招募信息
function ClassRef:getTeamRecruitInfoEndingModified()
	return self._data_temp:clone(), self._isMyTeamLeader
end

function ClassRef:registerOnOperate( cb )
	self._onPanelHandler = cb
end

return ClassRef
